package Controller;

import entity.Cake;
import entity.CakeData;
import entity.Cart;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

public class AddToCartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int cakeId = Integer.parseInt(request.getParameter("id"));
        Cake selectedCake = CakeData.getCakeById(cakeId);

        if (selectedCake != null) {
            HttpSession session = request.getSession();
            Cart cart = (Cart) session.getAttribute("cart");

            if (cart == null) {
                cart = new Cart();
                session.setAttribute("cart", cart);
            }

            cart.addItem(selectedCake);
        }

        response.sendRedirect("CakeListServlet");
    }
}